package com.snail.common.tenant.config;

import com.snail.common.tenant.constants.TenantConstants;
import com.snail.common.tenant.interceptor.TenantInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description: 多租户web配置类
 * @Author: Snail
 * @CreateDate: 2023/8/3 15:30
 * @Version: V1.0
 */
@Configuration
@EnableConfigurationProperties(TenantProperties.class)
@ConditionalOnProperty(name = "snail.tenant.enabled", havingValue = "true")
public class TenantWebConfig implements WebMvcConfigurer {

    @Autowired
    private TenantProperties tenantProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //多租户未开启
        if (!tenantProperties.isOpen()) {
            return;
        }
        //非数据库隔离
        if (!TenantConstants.TENANT_TYPE_DB.equals(tenantProperties.getType())) {
            return;
        }
        //添加多租户配置内容
        registry.addInterceptor(getTenantInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(tenantProperties.getExcludeUrls())
                .order(-10);
    }

    /**
     * 自定义请求拦截器
     */
    public TenantInterceptor getTenantInterceptor() {
        return new TenantInterceptor(tenantProperties);
    }
}
